<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/6
 * Time: 11:25
 */

namespace App\Http\Controllers\Home;

use App\Model\Apply;
use App\Model\MicroMall;
use App\Model\ShopMemberCart;
use App\Model\ShopOrder;
use App\Model\ShopOrderComment;
use Illuminate\Http\Request;
use App\Model\ShopGoods;
use App\Model\ShopGoodsImg;
use App\Model\ShopGoodsClassify;
use App\Model\Members;
use App\Model\GoodsSpecsVal;
use App\Model\GoodsSpecsName;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use App\Model\MembersLevel;

class ExcellentController extends BaseController
{
    /**
     * 超级商城首页
     */
    public function index(Request $request)
    {
        //检测是否填写资料
        $user = session('home_user');
        if ($user->isdown != 1) {
            return back()->withErrors('没有超级商城权限');
        }
        $UserModel = new Members();
        $userInfo = $UserModel->where('uid', $user['uid'])->first();
        Session::put('home_user', $userInfo);
        if (empty($userInfo['phone']) || empty($userInfo['user_name'])) {
            return redirect('home/member/userInfo')->withErrors('请完善个人资料');
        }
//        $userLeve = MembersLevel::where('id',$user['level'])->first();
//        if($user['credit3']>$userLeve['credit3']){
//            return redirect('home/straightShop/index')->withErrors('请复投');
//        }
        return view('Home.excellent.index');
    }

    /**
     * 购买页面
     */
    public function product()
    {
        return view('Home.excellent.product');
    }

    /**
     * 订单页面
     */
    public function order()
    {
        return view('Home.excellent.order');
    }

    /**
     * 优品特选商品表
     * @param Request $request
     * @return array
     * @throws \Exception
     */
    public function goods(Request $request)
    {
        $data = $request->all();
        if (empty($data)) {
            return ['code' => 0, 'data' => '参数错误'];
        }
        switch ($data['class']) {
            case 'select': //查询
                $table = ShopGoodsClassify::where(['enabled' => 1, 'pid' => 7])->select('id');
                $classify = $table->get()->toArray();
                $pid = ['7'];
                if (!empty($classify)) {
                    foreach ($classify as $value) {
                        $pid[] = $value['id'];
                    }
                } else {
                    return ['code' => 0, 'data' => '暂时还没有商品'];
                }
                //查询商品
                $shop = ShopGoods::where(['type' => 1, 'status' => 1])->whereIn('cid', $pid)->get()->toArray();
                shuffle($shop);
                //随机轮播图
                $rotation = ShopGoodsImg::join('shop_goods', 'shop_goods.id', '=', 'shop_goods_img.gid')
                    ->join('shop_goods_classify', 'shop_goods.cid', '=', 'shop_goods_classify.id')
                    ->select(
                        'shop_goods_img.gid', 'shop_goods_img.img'
                    )
                    ->where(['shop_goods.type' => 1, 'shop_goods.status' => 1, 'shop_goods_classify.type' => 1])
                    ->groupBy('shop_goods_img.gid')
                    ->inRandomOrder()
                    ->take(2)
                    ->get()
                    ->toArray();
                if ($shop) {
                    foreach ($shop as $k => $value) {
                        $img = ShopGoodsImg::where(['gid' => $value['id']])->select('img')->first();
                        if ($img) {
                            $shop[$k]['img'] = $img->img;
                        }
                    }
                }

                return ['code' => 1, 'data' => $shop, 'rotation' => $rotation];


                break;
            case 'add':    //添加 or 修改
                if ($data['goods']['id']) { //修改
                    $Rows = ShopGoods::where('id', $data['goods']['id'])->update($data['goods']);
                } else {
                    $data['createtime'] = time();
                    $Rows = ShopGoods::create($data['goods']);
                }
                //更新图片
                $goodsId = empty($data['goods']['id']) ? $Rows->id : $data['goods']['id'];
                $goodsImgName = empty($data['goodsImgName']) ? 0 : $data['goodsImgName'];
                $rico = $this->updateImg($goodsId, $goodsImgName);
                if ($Rows || $rico) {
                    return ['code' => 1, 'data' => '设置成功'];
                } else {
                    return ['code' => 0, 'data' => '设置失败'];
                }
                break;
            case 'find':   //查询一条数据
                $user = session('home_user');
                //查出该商品对应的所有规格名
                $GoodsSpecsName = GoodsSpecsName::where(['goods_id' => $data['id']])->select('id', 'name')->get()->toArray();
                //查出该商品的所有规格值
                $GoodsSpecsVal = [];
                if ($GoodsSpecsName) {
                    foreach ($GoodsSpecsName as $k => $v) {
                        $thisSpecsVal = GoodsSpecsVal::where(['specs_id' => $v['id']])->select('id', 'val', 'specs_id')->get()->toArray();
                        array_push($GoodsSpecsVal, ['specs_id' => $v['id'], 'vals' => $thisSpecsVal]);
                    }
                }

                $goods = ShopGoods::where('id', $data['id'])->first();
                if ($goods) {
                    if ($goods['is_gift'] == 1) {
                        $goods['is_gift'] = '包邮';
                    } else {
                        $goods['is_gift'] = '自提';
                    }
                    $orderData = ShopOrderComment::where('goodsid', $data['id'])
                        ->join('shop_order', 'shop_order.id', '=', 'shop_order_comment.orderid')
                        ->where('shop_order.status', '>=', 1)
                        ->join('members', 'shop_order_comment.uid', '=', 'members.uid')
                        ->select('members.name', 'shop_order.createtime')
                        ->orderBy('shop_order.createtime', 'DESC')
                        ->limit(5)
                        ->get();
                    foreach ($orderData as $k => $v) {
                        $orderData[$k]['createtime'] = date('Y-m-d H:i:s', $v['createtime']);
                        $orderData[$k]['name'] = MOBILE_PHONE_HIDDEN($v['name']);
                    }
                }
                $goodsImgName = json_decode($goods['rotation_chart']);
                if ($goodsImgName) {
                    $goodsList = array();
                    foreach ($goodsImgName as $k => $v) {
                        $goodsList[$k]['img'] = $v;
                    }
                    $goodsImgName = $goodsList;
                }
                if (empty($goodsImgName)) {
                    $goodsImgName = ShopGoodsImg::where('gid', $data['id'])->select('img')->get()->toArray();
                }
                if ($goods) {
                    return ['code' => 1, 'data' => ['goods' => $goods, 'goodsImgName' => $goodsImgName], 'GoodsSpecsName' => $GoodsSpecsName, 'GoodsSpecsVal' => $GoodsSpecsVal, 'orderData' => $orderData];
                } else {
                    return ['code' => 0, 'data' => '设置失败'];
                }
                break;
            case 'delete': //删除
                if ($data['id']) {
                    $rico = ShopGoods::where('id', $data['id'])->update(['type' => -1]);
                    if ($rico) {
                        return ['code' => 1, 'data' => '删除成功'];
                    } else {
                        return ['code' => 0, 'data' => '删除失败'];
                    }
                } else {
                    return ['code' => 0, 'data' => '数据错误'];
                }
                break;
        }
    }

    /**
     * 优品特选订单
     * @param Request $request
     * @return array
     * @throws \Exception
     */
    public function excellentOrder(Request $request)
    {
        $data = $request->all();
        if (empty($data)) {
            return ['code' => 0, 'data' => '没有数据'];
        }
        $user = session('home_user');
        //商品表
        $ShopGoodsModel = new ShopGoods();
        //复销折扣
        $microMallModel = new MicroMall();
        $microMall = $microMallModel->get()->toArray();
        //订单表
        $ShopOrderModel = new ShopOrder();
        //订单详情表
        $ShopOrderCommentModel = new ShopOrderComment();
        //购物车表
        $ShopMemberCartModel = new ShopMemberCart();
        switch ($data['class']) {
            case 'add': //添加
                if (empty($data['goods'])) {
                    return ['code' => 0, 'data' => '没有商品'];
                }
                $goodsIds = [];
                foreach ($data['goods'] as $k => $v) {
                    if (intval($v['number']) < 1 || intval($v['number']) == '') {
                        return ['code' => 0, 'data' => '数量错误'];
                        break;
                    }
                    $goodsIds[] = $v['goodsid'];
                }


                if (isset($data['type'])) {
                    $specs = $data['goods'][0]['specs'];
                    $specslength = $data['specslength'];
                    $Checklength = $data['Checklength'];
                    $specsExist = $data['specsExist'];
                    if ($specsExist == 1 && $specs == '') {
                        return ['code' => 0, 'data' => '请选择产品规格'];
                    }
                    if ($specsExist == 1) {
                        if ($specslength != $Checklength) {
                            return ['code' => 0, 'data' => '请完整选择产品规格!'];
                        }
                    }
                }

                DB::beginTransaction(); //开启事务
                $goods = $ShopGoodsModel->get_goods('', $goodsIds);
                $totalPrice = 0;   //总价格
                $number = 0;
                $freight = 0;//运费
//                $weight = 0;//重量
//                $freight_cost = 1;//是否需要算运费
                foreach ($goods as $k => $v) {
                    foreach ($data['goods'] as $key => $val) {
                        if ($val['goodsid'] == $v['id']) {
                            $number += $val['number'];
//                            $weight += ($val['number'] * $v['weight']);
//                            var_dump($val['number']);exit;
                            $data['goods'][$key]['sold'] = $val['number'] + $v['sold'];
                            $totalPrice += (intval($val['number']) * $v['rulingprice']);
                            $data['goods'][$key]['price'] = $v['rulingprice'];
                            $data['goods'][$key]['totalcnf'] = $v['totalcnf']; //0 拍下减库存 1 付款减库存 2 永久不减
                            $data['goods'][$key]['total'] = $v['total'];
                            $data['goods'][$key]['goodsname'] = $v['goodsname']; //商品名字
                        }
                    }
                }
//                if ($freight_cost == 1) {
//                    $weight = ceil($weight);
//                    $freight = ($weight > 1) ? ($weight - 1) * 5 + $freight : $freight;
//                    $totalPrice = intval($totalPrice * 100) / 100; //保留两位小数
//                } else {
//                    $freight = 0;
//                    $totalPrice = intval($totalPrice * 100) / 100; //保留两位小数
//                }
                //根据会员等级计算折扣
                $user = Members::where('uid', $user->uid)->first();
                $userCity = Apply::where(['uid' => $user['uid'], 'type' => 1, 'status' => 1])->count();
                $district = Apply::where(['uid' => $user['uid'], 'type' => 2, 'status' => 1])->count();
//                if ($userCity > 0){
//                    $totalPrice = RETAIN_TWO($totalPrice * $microMall[3]['discount']/10);
//                } else if ($district > 0){
//                    $totalPrice = RETAIN_TWO($totalPrice * $microMall[2]['discount']/10);
//                } else if ($user['super_level'] == 2){
//                    $totalPrice = RETAIN_TWO($totalPrice * $microMall[1]['discount']/10);
//                } else {
//                    $totalPrice = RETAIN_TWO($totalPrice * $microMall[0]['discount']/10);
//                }
                //创建订单
                $order = [
                    'uid' => $user->uid,
                    'openid' => $user->openid,
                    'ordertype' => 1, //1 优品特选 2 微商城 3 0元商城
                    'ordersn' => ORDER_SN(),
                    'price' => $totalPrice,
                    'originalprice' => $totalPrice,
                    'freight' => $freight, //运费
                    'company_id' => $user->company_id, //公司id
                    'status' => 0,//-1取消状态，0代付款，1为已付款，2为已发货，3为成功
                    'createtime' => time()
                ];
                $orderID = $ShopOrderModel->add_order($order);


                if ($orderID) {

                    $cart = array(); //购物车id
                    $orderComment = array();
                    foreach ($data['goods'] as $key => $val) {
                        $cart[] = $val['id']; //获取购物车id
                        $orderComment[] = [
                            'uid' => $user->uid,
                            'orderid' => $orderID,
                            'openid' => $user->openid,
                            'goodsid' => $val['goodsid'],
                            'price' => $val['price'],
                            'goodsname' => $val['goodsname'],
                            'number' => $val['number'],
                            'specs' => $val['specs'],
                            'createtime' => time(),
                        ];
                    }

                    if (!empty($orderComment)) {
                        $rico = $ShopOrderCommentModel->insert($orderComment);
                        if ($rico) {
                            //直接购买
                            if (isset($data['type'])) {
                                DB::commit();  //提交
                                return ['code' => 1, 'data' => ['id' => $orderID, 'data' => '添加成功']];
                            }
                            //删除购物车
                            $Comment = $ShopMemberCartModel->delete_cart($cart);
                            if ($Comment) {
                                DB::commit();  //提交
                                return ['code' => 1, 'data' => ['id' => $orderID, 'data' => '添加成功']];
                            } else {
                                DB::rollback();  //回滚
                                return ['code' => 0, 'data' => '购物车已清空'];
                            }
                        } else {
                            DB::rollback();  //回滚
                            return ['code' => 0, 'data' => '添加失败'];
                        }
                    }
                } else {
                    DB::rollback();  //回滚
                    return ['code' => 0, 'data' => '设置失败'];
                }
                break;

        }
    }

    /**
     * 判断商品是否有规格
     * @param Request $request
     * @return array
     */

    public function isSpecs(Request $request)
    {
        $data = $request->all();
//        var_dump($data);die;
        $specsCount = GoodsSpecsName::where('goods_id', $data['gid'])->count();
        $GoodsSpecsName = GoodsSpecsName::where(['goods_id' => $data['gid']])->select('id', 'name')->get()->toArray();
        $GoodsSpecsVal = [];
        if ($GoodsSpecsName) {
            foreach ($GoodsSpecsName as $k => $v) {
                $thisSpecsVal = GoodsSpecsVal::where(['specs_id' => $v['id']])->select('id', 'val', 'specs_id')->get()->toArray();
                array_push($GoodsSpecsVal, ['specs_id' => $v['id'], 'vals' => $thisSpecsVal]);
            }
        }
        if ($specsCount > 0) {
            return ['code' => 1, 'GoodsSpecsName' => $GoodsSpecsName, 'GoodsSpecsVal' => $GoodsSpecsVal];
        } else {
            return ['code' => 0];
        }
    }


}